//
//  EditAvatarVC.m
//  Common
//
//  Created by xiang ji on 2018/8/2.
//

#import "EditAvatarVC.h"
#import <QuartzCore/QuartzCore.h>

@interface EditAvatarVC ()<UIGestureRecognizerDelegate>
{
    UIPinchGestureRecognizer *pinchRecognizer;
    UIRotationGestureRecognizer *rotationRecognizer;
    UIPanGestureRecognizer *panRecognizer;
    
    UIImageView *_maskImageView;
    CGRect _clippingRect;           //裁剪的区域
}
@property (nonatomic, strong)  UIImageView *avatarImageView;
@property (nonatomic, strong)  UIView *avatarContainer;

@end

@implementation EditAvatarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createNavBarRightButtonWithName:@"保存"];
    WEAKSELF
    self.rightNavButtonBlock = ^{
        [weakSelf uploadAvatar];
    };
    [self customView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setupInterface];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setHidesBottomBarWhenPushed:YES];
    }
    
    return self;
}

- (void)uploadAvatar {
    UIImage *avatarImage = [self createFinalImage];
    if (avatarImage != nil) {
        if (self.getImage) {
            self.getImage(avatarImage);
            [self dismissVC];
        }
    }
}

-(UIView *)avatarContainer
{
    if (!_avatarContainer) {
        _avatarContainer = [[UIView alloc] initWithFrame:self.view.frame];
        [_avatarContainer addSubview:self.avatarImageView];
        [_avatarContainer setBackgroundColor:[UIColor blackColor]];
    }
    return _avatarContainer;
}

-(UIImageView *)avatarImageView
{
    if (!_avatarImageView) {
        _avatarImageView = [[UIImageView alloc] initWithFrame:_avatarContainer.frame];
        _avatarImageView.contentMode=UIViewContentModeScaleAspectFit;
    }
    return _avatarImageView;
}

#pragma mark - 定制view
- (void)customView
{
    // 设置标题
    self.title = @"图片裁剪";
    self.view.backgroundColor = [EPColor epColor_Bg];
    [self.view addSubview:self.avatarContainer];
    
    //手势：
    pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(onImageScale:)];
    [pinchRecognizer setDelegate:self];
    [self.view addGestureRecognizer:pinchRecognizer];
    
//    rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(onImageRotate:)];
//    [rotationRecognizer setDelegate:self];
//    [self.view addGestureRecognizer:rotationRecognizer];
    
    panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onImageMove:)];
    [panRecognizer setMinimumNumberOfTouches:1];
    [panRecognizer setMaximumNumberOfTouches:1];
    [panRecognizer setDelegate:self];
    [self.view addGestureRecognizer:panRecognizer];
}

#pragma mark - UI
- (void)setupInterface {
    
    /**
     *  加载头像原始图片
     */
    if (self.avatarImage) {
        self.avatarImageView.image = self.avatarImage;
        self.avatarImageView.center = self.avatarContainer.center;   //居中显示
    }
    
    /**
     *  创建遮罩层
     */
    if (_maskImageView) {
        [_maskImageView removeFromSuperview];
        _maskImageView = nil;
    }
    
    UIImage *maskImage = [self createMaskImage];
    _maskImageView = [[UIImageView alloc] initWithImage:maskImage];
    _maskImageView.userInteractionEnabled = NO;
    
    [self.view addSubview:_maskImageView];
}

/**
 *  创建圆形遮罩：
 *
 *  @return 图片
 */
- (UIImage *)createMaskImage {
    
    CGRect frame = self.view.frame;
    
    UIGraphicsBeginImageContext(frame.size);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.6);
    
    CGRect drawRect = CGRectMake(0, 0, frame.size.width, frame.size.height);
    
    CGContextFillRect(ctx, drawRect);   //draw the transparent layer
    
    float screenWidth = frame.size.width;
    float width = screenWidth * 2 / 3;
    float height = width;
    
    if (self.isRectangle) {
        width = screenWidth * 4 / 5;
        height = width * 3 / 4;
    }
    
    float x = frame.size.width/2 - width/2;
    float y = frame.size.height/2 - height/2;
    
//    CGContextStrokeRect(ctx,CGRectMake(x, y, width, height));//画方框
    CGContextSetLineWidth(ctx, 1.0);//线的宽度
    UIColor *aColor = [UIColor whiteColor];
    CGContextSetStrokeColorWithColor(ctx, aColor.CGColor);//线框颜色
    CGContextAddRect(ctx,CGRectMake(x, y, width, height));//画方框
    CGContextDrawPath(ctx, kCGPathFillStroke);//绘画路径
    
    _clippingRect = CGRectMake(x, y, width, height);
//    CGContextAddEllipseInRect(ctx, _clippingRect);  //圆形遮罩图
    CGContextClip(ctx);
    CGContextClearRect(ctx, _clippingRect);
    
    UIImage* returnimage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return returnimage;
}


#pragma mark - Gesture
- (void)onImageScale:(UIGestureRecognizer *)recognizer {
    
    UIPinchGestureRecognizer *pinchGesture = (UIPinchGestureRecognizer*)recognizer;
    
    static float lastScale = 1.0;
    if(pinchGesture.state == UIGestureRecognizerStateBegan) {
        lastScale = 1.0;
    }
    
    CGFloat scale = 1.0 - (lastScale - [pinchGesture scale]);
    
    CGAffineTransform currentTransform = self.avatarImageView.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    
    [self.avatarImageView setTransform:newTransform];
    
    lastScale = [pinchGesture scale];
}

- (void)onImageRotate:(UIRotationGestureRecognizer *)recognizer {
    
    UIRotationGestureRecognizer *rotateGesture = (UIRotationGestureRecognizer*)recognizer;
    
    static float _lastRotation = 0.0;
    if([rotateGesture state] == UIGestureRecognizerStateEnded) {
        _lastRotation = 0.0;
        return;
    }
    
    CGFloat rotation = 0.0 - (_lastRotation - [rotateGesture rotation]);
    
    CGAffineTransform currentTransform = self.avatarImageView.transform;
    CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform,rotation);
    
    [self.avatarImageView setTransform:newTransform];
    
    _lastRotation = [rotateGesture rotation];
}

- (void)onImageMove:(UIGestureRecognizer *)recognizer {
    
    UIPanGestureRecognizer *panGesture = (UIPanGestureRecognizer*)recognizer;
    
    CGPoint point = [panGesture translationInView:self.view];
    
    static float x = 0;
    static float y = 0;
    
    if (panGesture.state == UIGestureRecognizerStateBegan) {
        x = self.avatarImageView.center.x;
        y = self.avatarImageView.center.y;
    }
    
//    DDLogDebug(@"Point: %f, %f", point.x, point.y);
//    DDLogDebug(@"Center: %f, %f", x, y);
    
    CGPoint center = CGPointMake(x + point.x, y + point.y);
    [self.avatarImageView setCenter:center];
}

- (UIImage *)createFinalImage {
    
    UIGraphicsBeginImageContextWithOptions(self.avatarContainer.bounds.size, YES, 0);
    [self.avatarContainer drawViewHierarchyInRect:self.avatarContainer.bounds afterScreenUpdates:YES];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //选择区域，x倍率：
    float scale = [UIScreen mainScreen].scale;
    CGRect frame = _clippingRect;
    frame.origin.x *= scale;
    frame.origin.y *= scale;
    frame.size.width *= scale;
    frame.size.height *= scale;
    
    //裁切图片：
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], frame);
    UIImage *finalImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    
    return finalImage;
}

@end
